<template>
  <div ref="container_ref">
    <a-select :getPopupContainer="() => container_ref" :value="selectModel" mode="multiple" label-in-value
      placeholder="输入机构名称" :autoAdjustOverflow="false"
      style=" width: 100%; border-left: 1px solid rgb(224, 226, 235);border-radius: 0; background-color: transparent;"
      :popupClassName="`${'nurse-hospital'}`" :filter-option="false"
      :not-found-content="nurseHospital.fetching ? undefined : null" @search="fetchNurseHospital"
      @change="selectChange">
      <template v-if="nurseHospital.fetching" #notFoundContent>
        <a-spin size="small" />
      </template>
      <template v-for="option of nurseHospital.data" :key="option.id">
        <a-select-option :value="option.id">
          <div title="" class="w-full flex  justify-between items-center">
            <div>{{ option.name }}</div>
          </div>
        </a-select-option>
      </template>
    </a-select>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';

// 定义 props 和 emits
const props = defineProps({
  value: {
    type: String,
    default: '',  // 期望传入一个逗号分隔的字符串
  },
});

const emit = defineEmits(['update:value']);

const container_ref = ref(null)

const nurseHospital = reactive<any>({
  data: [],
  value: [],
  fetching: false,
});

const fetchNurseHospital = async () => {
  nurseHospital.data = [];
  nurseHospital.fetching = true;
  const { records } = await defHttp.get({
    url: "/nurse_hospital/nurseHospital/rootList"
  });
  if (records && records.length > 0) {
    nurseHospital.data = Object.freeze(records)
  }
  nurseHospital.fetching = false;
}
const selectModel = computed(() => {
  return props.value ? props.value.split(',').map((v) => v.trim()) : [];
});
function selectChange(v: any[]) {
  if (!v || v.length === 0) {
    emit('update:value', ''); // 如果为空，则传递空字符串
    return;
  }

  // 提取每个对象的 value 属性，形成新数组
  const valueArray = v.map(item => item.value);

  // 将数组中的值合并为逗号分隔的字符串
  const newValue = valueArray.join(',');
  // 向父组件传递更新后的值
  emit('update:value', newValue);
}
onMounted(() => {
  fetchNurseHospital()
})
</script>

<style lang="less" scoped>
:deep(.nurse-hospital) {
  position: absolute !important;
  left: 0 !important;
  top: 100% !important;
  overflow-y: auto !important;
  transform: translateY(0) !important;
}
</style>
